from django.http import JsonResponse
from web.models import PlatformUserV2
from django import forms
from django.forms.models import model_to_dict
import uuid
from web.apis import tools
import re
import json
"""
错误码:
0: 成功
1: 失败
2: 参数错误
3: 请求方式错误
4: 安全验证失败
5: 权限不足
"""



# 平台用户表单
class PlatformUserV2Form(forms.ModelForm):
    class Meta:
        model = PlatformUserV2
        fields = [
            'account',
            'password',
        ]

    def clean_password(self):
        password = self.cleaned_data.get('password')
        if len(password) < 6:
            raise forms.ValidationError('密码长度不能小于6位')
        if not re.match(r'^[a-zA-Z0-9@]{6,12}$', password):
            raise forms.ValidationError('密码只能包含大小写英文、数字、@符号')
        return password

    def clean_account(self):
        account = self.cleaned_data.get('account')
        if not re.match(r'^\d{6,11}$', account):
            raise forms.ValidationError('账号只能是6-11位数字')
        return account

def model_to_dict_with_url(model, **kwargs):
    """
    kwargs:
        - is_del_password: 是否删除密码 bool 默认 True
    """
    model_dict = model_to_dict(model)
    model_dict['create_time'] = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
    model_dict['update_time'] = model.update_time.strftime('%Y-%m-%d %H:%M:%S')
    if kwargs.get('is_del_password', True):
        model_dict.pop('password')
    return model_dict

# 创建平台用户
def create_platform_user(request):
    if request.method != 'POST':
        return JsonResponse(tools.ReturnData(code=3, msg='请使用POST方法请求'))

    try:
        form = PlatformUserV2Form(request.POST)
        if not form.is_valid():
            error_msg = tools.get_first_error(form)
            print(form.errors)
            return JsonResponse(tools.ReturnData(code=2, msg=error_msg))
        form.save()
        platform_user = form.instance
        # 获取请求中携带的其它参数
        other_params = request.POST.get('other_params')
        # if other_params:
        #     # ⇄ JSON 字符串转字典
        #     other_params = json.dumps(other_params)
        # 通知对方的服务器
        tools.send_platform_info_msg(
            request.POST.get('redirect'),
            {"user_id":form.instance.user_id, "other_params":other_params}
        )
        return JsonResponse(tools.ReturnData(code=0, msg='平台用户创建成功', data=model_to_dict_with_url(platform_user)))

    except Exception as e:
        return JsonResponse(tools.ReturnData(code=1, msg='创建平台用户失败，请稍后重试', data=str(e)))

# 获取平台用户
def get_platform_user(request):
    if request.method != 'POST':
        return JsonResponse(tools.ReturnData(code=3, msg='请使用POST方法请求'))

    user_id = request.POST.get('user_id')

    if not user_id:
        return JsonResponse(tools.ReturnData(code=2, msg='请提供用户ID'))

    try:
        platform_user = PlatformUserV2.objects.filter(user_id=user_id).first()
        if not platform_user:
            return JsonResponse(tools.ReturnData(code=1, msg='未找到该平台用户'))

        return JsonResponse(tools.ReturnData(code=0, msg='获取平台用户成功', data=model_to_dict_with_url(platform_user)))

    except Exception:
        return JsonResponse(tools.ReturnData(code=1, msg='获取平台用户失败，请稍后重试'))

# 更新平台用户
def update_platform_user(request):
    if request.method != 'POST':
        return JsonResponse(tools.ReturnData(code=3, msg='请使用POST方法请求'))

    user_id = request.POST.get('user_id')

    if not user_id:
        return JsonResponse(tools.ReturnData(code=2, msg='请提供用户ID'))

    try:
        platform_user = PlatformUserV2.objects.filter(user_id=user_id).first()
        if not platform_user:
            return JsonResponse(tools.ReturnData(code=1, msg='未找到该平台用户'))

        form = PlatformUserV2Form(request.POST, instance=platform_user)
        if not form.is_valid():
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=2, msg=error_msg))

        updated_user = form.save()
        return JsonResponse(tools.ReturnData(code=0, msg='平台用户更新成功', data=model_to_dict_with_url(updated_user)))

    except Exception:
        return JsonResponse(tools.ReturnData(code=1, msg='更新平台用户失败，请稍后重试'))

# 删除平台用户
def delete_platform_user(request):
    if request.method != 'POST':
        return JsonResponse(tools.ReturnData(code=3, msg='请使用POST方法请求'))

    user_id = request.POST.get('user_id')

    if not user_id:
        return JsonResponse(tools.ReturnData(code=2, msg='请提供用户ID'))

    try:
        platform_user = PlatformUserV2.objects.filter(user_id=user_id).first()
        if not platform_user:
            return JsonResponse(tools.ReturnData(code=1, msg='未找到该平台用户'))

        platform_user.delete()

        return JsonResponse(tools.ReturnData(code=0, msg='平台用户删除成功'))

    except Exception:
        return JsonResponse(tools.ReturnData(code=1, msg='删除平台用户失败，请稍后重试'))

# 通过账号、密码查询,适用于用户登录
def get_platform_user_by_account_and_password(request):
    if request.method != 'POST':
        return JsonResponse(tools.ReturnData(code=3, msg='请使用POST方法请求'))

    account = request.POST.get('account')
    password = request.POST.get('password')

    if not all([account, password]):
        return JsonResponse(tools.ReturnData(code=2, msg='请提供账号和密码'))

    try:
        platform_user = PlatformUserV2.objects.filter(account=account, password=password).first()
        if not platform_user:
            return JsonResponse(tools.ReturnData(code=1, msg='账号或密码错误'))

        # 通知对方的服务器
        tools.send_platform_info_msg(
            request.POST.get('redirect'),
            {"user_id":platform_user.user_id, "other_params":request.POST.get('other_params')}
        )
        return JsonResponse(tools.ReturnData(code=0, msg='登录成功', data=model_to_dict_with_url(platform_user)))

    except Exception:
        return JsonResponse(tools.ReturnData(code=1, msg='登录失败，请稍后重试'))

